package com.singerw.aspect;

import com.alibaba.fastjson.JSONObject;
import com.singerw.annotations.OperLog;
import com.singerw.service.LogService;
import com.singerw.utils.JwtUtils;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;

import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Method;
import java.util.Date;

/**
 * @version V1.0
 * @Package com.singerw.aspect
 * @auhter 张欣
 * @date 2021/1/23-5:29 PM
 */
@Aspect
@Component
public class OperLogAspect {

    @Autowired
    private LogService logService;

    @Pointcut("@annotation(com.singerw.annotations.OperLog)")
    public void operLogPoinCut() {
    }

    @AfterReturning(value = "operLogPoinCut()", returning="returnValue")
    public void saveOperLog(JoinPoint joinPoint, Object returnValue) {
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        Method method = signature.getMethod();
        OperLog opLog = method.getAnnotation(OperLog.class);
        RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = (HttpServletRequest) requestAttributes.resolveReference(RequestAttributes.REFERENCE_REQUEST);
        String Authorization = request.getHeader("Authorization");
        String username = JwtUtils.getUsername(Authorization);
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("operModul", opLog.operModul());
        jsonObject.put("operType", opLog.operType());
        jsonObject.put("operDesc", opLog.operDesc());
        jsonObject.put("userName", username);
        jsonObject.put("date", new Date());
        logService.addLog(jsonObject);


    }

}
